package com.example.demo.example.properties;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author libo
 * @ClassName PropertiesUtils
 * @date 2019/3/1 17:50
 */
public class PropertiesUtils {
    public static  final  ConcurrentHashMap<String,Properties> map = new ConcurrentHashMap<String,Properties>();

    public static Properties getProperties(String path){
        Properties result = map.get(path);
        if(result != null){
            return  result;
        }
        result = new Properties();
        try{
            /*InputStream is = new FileInputStream(path);
            result.load(is);*/
            //InputStream inputStream = PropertiesUtils.class.getResourceAsStream(path);
            InputStream inputStream_1  = PropertiesUtils.class.getClassLoader().getResourceAsStream(path);
            //result.load(inputStream);
            result.load(inputStream_1);
        }catch (Exception e){
            /*try {
                result.load(PropertiesUtils.class.getClassLoader().getResourceAsStream(path));
            }catch (Exception e1){
                e1.printStackTrace();*/
                e.printStackTrace();
                return null;
           // }
        }
        map.put(path, result);
        return  result;
    }

    public static String  getString(String path,String key){
        Properties p = getProperties(path);
        if (p == null) {
            return  null;
        }
        return p.getProperty(key);
    }

    public static List<String> getList(String path,String key){
        String value = getString(path,key);
        List<String> result = new ArrayList<>();
        if(value.length() == 0){
            return  result;
        }
        String [] value_s = value.split(",");
        for (String s: value_s) {
            result.add(s);
        }
        return  result;
    }

    public static Map<String,String> getMap(String path,String key){
        String value = getString(path,key);
        Map<String,String> result = new HashMap<>();
        if(value.length() == 0){
            return  result;
        }
        String[] value_s = value.split(",");
        for (String s : value_s) {
            String[] key_value = s.split(":");
            result.put(key_value[0], key_value[1]);
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(PropertiesUtils.getString("application.properties", "server.context-path"));
    }

}
